﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Data;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace SlvPartecipazione.Web
{
    public partial class ViewResults : System.Web.UI.Page
    {
        DataSet myDataSet = new DataSet();
        XDocument xml = XDocument.Load("http://www.sanitelitalia.it/TEST/ListaPartecipanti.xml");
        string xmlStr = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //getDataSet_report_partite();

                bindGridView("", "");

                bindGridInAttesa();

                ViewState["sortOrder"] = "";
            }
        }

        //public void getDataSet_report_partite()
        //{
        //    WebClient webClient = new WebClient();
        //    string xmlStr = webClient.DownloadString("http://www.sanitelitalia.it/aspx/slvajax.aspx?op=report_partite");

        //    MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(xmlStr));

        //    myDataSet.ReadXml(ms, XmlReadMode.DiffGram);
        //}

        public void bindGridInAttesa()
        {
            XDocument report = XDocument.Parse(xmlStr);// Load("http://www.sanitelitalia.it/aspx/slvajax.aspx?op=report_partite");

            var q = from c in xml.Descendants("PARTECIPANTE")
                    where !(from g in report.Descendants("GUID")
                            select g.Value).Contains(c.Element("GUID").Value)
                             && c.Element("NOME").Value != ""
                    select new { alias = c.Element("ALIAS").Value, nome = c.Element("NOME").Value };

            GridInAttesa.DataSource = q;
            GridInAttesa.DataBind();

        }
        
        public void bindGridView(string sortExp, string sortDir)
        {
            WebClient webClient = new WebClient();

            xmlStr = webClient.DownloadString("http://www.sanitelitalia.it/aspx/slvajax.aspx?op=report_partite");

            MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(xmlStr));

            myDataSet.ReadXml(ms, XmlReadMode.DiffGram);

            myDataSet.Tables[0].Columns.Add("NOME");
            myDataSet.Tables[0].Columns["NOME"].SetOrdinal(2);

            foreach (System.Data.DataRow dr in myDataSet.Tables[0].Rows)
            {
                //dr.BeginEdit();

                var q = from c in xml.Descendants("PARTECIPANTE")
                        where c.Element("GUID").Value == dr["GUID"].ToString()
                        select new { alias = c.Element("ALIAS").Value, nome = c.Element("NOME").Value };

                //dr["GUID"] = q.FirstOrDefault().alias;
                //dr["NOME"] = q.FirstOrDefault().nome;

                if (q.FirstOrDefault() != null)
                {
                    var obj = q.FirstOrDefault();
                    dr["GUID"] = obj.alias;
                    dr["NOME"] = obj.nome;
                }
                else
                {
                    dr["GUID"] = "";
                    dr["NOME"] = "";
                }

                dr.AcceptChanges();
            }

            myDataSet.Tables[0].Columns["GUID"].ColumnName = "ALIAS";

            myDataSet.AcceptChanges(); 

            DataView myDataView = new DataView();
            myDataView = myDataSet.Tables[0].DefaultView;

            if (sortExp != string.Empty)
            {
                myDataView.Sort = string.Format("{0} {1}", sortExp, sortDir);
            }

            //var q = from c in xml.Descendants("PARTECIPANTE")
            //        orderby sortExp
            //        select new { nome = c.Element("NOME").Value };

            GridResults.DataSource = myDataView;
            GridResults.DataBind();
        }

        protected void GridResults_Sorting(object sender, GridViewSortEventArgs e)
        {
            bindGridView(e.SortExpression, sortOrder);
            ViewState["sortExpression"] = e.SortExpression;

        }

        public string sortOrder
        {
            get
            {
                if (ViewState["sortOrder"].ToString() == "desc")
                {
                    ViewState["sortOrder"] = "asc";
                }
                else
                {
                    ViewState["sortOrder"] = "desc";
                }

                return ViewState["sortOrder"].ToString();
            }
            set
            {
                ViewState["sortOrder"] = value;
            }
        }
        
        protected void GridResults_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridResults.PageIndex = e.NewPageIndex;

            if (!String.IsNullOrEmpty( ViewState["sortExpression"].ToString()))
                bindGridView(ViewState["sortExpression"].ToString(), "");
        }

        protected void GridResults_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //string guid = ((System.Data.DataRowView)(e.Row.DataItem)).Row.ItemArray[1].ToString();

                //var q = from c in xml.Descendants("PARTECIPANTE")
                //        where c.Element("GUID").Value == guid
                //        select c.Element("NOME").Value;

                //e.Row.Cells[1].Text = q.FirstOrDefault<string>();


                e.Row.Cells[3].Text = (float.Parse(e.Row.Cells[3].Text) / 10).ToString("0.0") + " sec.";

            }
        }

    }
}